package com.study4j.common.utils;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.study4j.common.model.RequestHeader;
import com.study4j.common.model.RequestModel;

import cn.hutool.core.util.StrUtil;

/**
 * @description 请求实体工具类
 * @author jiangbin
 */
public class RequestUtil {

	/**
	 * @description 将请求数据由json数据转换成请求实体(从HttpServletRequest中获取并转换)
	 * @param request
	 * @param t
	 * @return
	 */
	public static <T> RequestModel<T> getRequestModel(HttpServletRequest request, Class<T> t) {
		RequestModel requertModel = new RequestModel();
		String header = request.getParameter("header");
		if (StrUtil.isNotEmpty(header)) {
			RequestHeader body = (RequestHeader) JSON.parseObject(header, RequestHeader.class);
			requertModel.setHeader(body);
		}

		if (t != null) {
			String body1 = request.getParameter("body");
			if (StrUtil.isNotEmpty(body1)) {
				requertModel.setBody(JSON.parseObject(body1, t));
			}
		}

		return requertModel;
	}

	/**
	 * @description 将json格式的请求数据转换成请求实体
	 * @param header
	 * @param body
	 * @param t
	 * @return
	 */
	public static <T> RequestModel<T> getRequestModel(RequestHeader header, String body, Class<T> t) {
		RequestModel requertModel = new RequestModel();
		requertModel.setHeader(header);
		if (t != null && StrUtil.isNotEmpty(body)) {
			requertModel.setBody(JSON.parseObject(body, t));
		}

		return requertModel;
	}

	/**
	 * @description 将json格式的请求数据转换成请求实体
	 * @param header
	 * @param body
	 * @param t
	 * @return
	 */
	public static <T> RequestModel<T> getRequestModel(String header, String body, Class<T> t) {
		RequestModel requertModel = new RequestModel();
		requertModel.setHeader((RequestHeader) JsonUtil.json2Object(header, RequestHeader.class));
		if (t != null && StrUtil.isNotEmpty(body)) {
			requertModel.setBody(JsonUtil.json2Object(body, t));
		}

		return requertModel;
	}
}